package com.innovation.ic.b1b.monitor.base.service.masterSlave.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.b1b.monitor.base.mapper.SqlServerAvailableJobMapper;
import com.innovation.ic.b1b.monitor.base.mapper.SqlServerMapper;
import com.innovation.ic.b1b.monitor.base.model.SqlServer;
import com.innovation.ic.b1b.monitor.base.model.SqlServerAvailableJob;
import com.innovation.ic.b1b.monitor.base.pojo.SqlServerPojo;
import com.innovation.ic.b1b.monitor.base.pojo.constant.TableNameConstant;
import com.innovation.ic.b1b.monitor.base.pojo.variable.ServiceResult;
import com.innovation.ic.b1b.monitor.base.pojo.variable.sqlServer.SqlServerInfoRespPojo;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.EnvironmentService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ServiceHelper;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.SqlServerAvailableJobLogHistoryService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.SqlServerAvailableJobLogService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.SqlServerService;
import com.innovation.ic.b1b.monitor.base.vo.SqlServerVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SqlServerServiceImpl extends ServiceImpl<SqlServerMapper, SqlServer> implements SqlServerService {

    @Resource
    private EnvironmentService environmentService;

    @Resource
    private SqlServerAvailableJobLogService sqlServerAvailableJobLogService;

    @Resource
    private SqlServerAvailableJobMapper sqlServerAvailableJobMapper;


    @Resource
    private SqlServerAvailableJobLogHistoryService sqlServerAvailableJobLogHistoryService;

    @Resource
    private ServiceHelper serviceHelper;


    @Override
    public ServiceResult addSqlServer(SqlServerVo sqlServerVo) {
        ServiceResult serviceResult = new ServiceResult();
        QueryWrapper<SqlServer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", sqlServerVo.getName());
        queryWrapper.eq("system_id", sqlServerVo.getSystemId());
        queryWrapper.eq("environment_id", sqlServerVo.getEnvironmentId());
        queryWrapper.eq("url", sqlServerVo.getUrl());
        Integer id = sqlServerVo.getId();
        SqlServer sqlServer = new SqlServer();
        BeanUtil.copyProperties(sqlServerVo, sqlServer);
        if (id == null) {
            List<SqlServer> sqlServers = this.baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(sqlServers)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("重复,请重新添加");
                return serviceResult;
            }

            QueryWrapper<SqlServer> queryWrapperName = new QueryWrapper<>();
            queryWrapperName.eq("name", sqlServerVo.getName());
            List<SqlServer> sqlServerName = this.baseMapper.selectList(queryWrapperName);
            if (!CollectionUtils.isEmpty(sqlServerName)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("名字不能重复");
                return serviceResult;
            }
            this.baseMapper.insert(sqlServer);
        } else {
            queryWrapper.ne("id", id);
            List<SqlServer> sqlServers = this.baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(sqlServers)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("重复,请重新添加");
                return serviceResult;
            }
            QueryWrapper<SqlServer> queryWrapperName = new QueryWrapper<>();
            queryWrapperName.eq("name", sqlServerVo.getName());
            queryWrapperName.ne("id", id);
            List<SqlServer> sqlServerName = this.baseMapper.selectList(queryWrapperName);
            if (!CollectionUtils.isEmpty(sqlServerName)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("名字不能重复");
                return serviceResult;
            }
            this.baseMapper.updateById(sqlServer);
        }
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage("成功");
        return serviceResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSqlServer(SqlServerVo sqlServerVo) {
        Integer id = sqlServerVo.getId();
        this.baseMapper.deleteById(id);
        this.deleteBySqlServerId(id);
    }

    @Override
    public SqlServerPojo findById(SqlServerVo sqlServerVo,Boolean mainDb) {
        return this.baseMapper.findById(sqlServerVo.getId());
    }

    @Override
    public ServiceResult<PageInfo<SqlServerPojo>> findByPage(SqlServerVo sqlServerVo,Boolean mainDb) {
        ServiceResult<PageInfo<SqlServerPojo>> serviceResult = new ServiceResult<>();
        //当环境id不为空时
        Integer environmentId = sqlServerVo.getEnvironmentId();
        if (environmentId != null) {
            List<Integer> environmentIds = environmentService.findByName(environmentId);
            if (!CollectionUtils.isEmpty(environmentIds)) {
                sqlServerVo.setEnvironmentIds(environmentIds);
            }
        }
        PageHelper.startPage(sqlServerVo.getPageNo(), sqlServerVo.getPageSize());
        List<SqlServerPojo> sqlServerPojoList = this.baseMapper.findByPage(sqlServerVo);
        PageInfo<SqlServerPojo> pageInfo = new PageInfo<>(sqlServerPojoList);
        serviceResult.setResult(pageInfo);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public void deleteBySystemId(Integer systemId) {
        Map<String, Object> map = new HashMap<>();
        map.put("system_id", systemId);
        this.baseMapper.deleteByMap(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByEnvironmentId(Integer environmentId) {
        QueryWrapper<SqlServer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("environment_id", environmentId);
        List<SqlServer> sqlServerList = this.baseMapper.selectList(queryWrapper);
        for (SqlServer sqlServer : sqlServerList) {
            Integer id = sqlServer.getId();
            this.deleteBySqlServerId(id);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("environment_id", environmentId);
        this.baseMapper.deleteByMap(map);
    }

    /**
     * 查询sql server信息列表
     *
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<SqlServerInfoRespPojo>> querySqlServerList(Boolean mainDb) {
        List<SqlServerInfoRespPojo> list = this.baseMapper.querySqlServerList();

        ServiceResult<List<SqlServerInfoRespPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(list);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }


    /**
     * 删除所有关联
     *
     * @param sqlServerId
     */
    private void deleteBySqlServerId(Integer sqlServerId) {
        //删除定时任务
        Map<String, Object> sqlServerIdMap = new HashMap<>();
        sqlServerIdMap.put("sql_server_id", sqlServerId);
        List<SqlServerAvailableJob> sqlServerAvailableJobs = sqlServerAvailableJobMapper.selectByMap(sqlServerIdMap);
        for (SqlServerAvailableJob sqlServerAvailableJob : sqlServerAvailableJobs) {
            Integer sqlServerAvailableJobId = sqlServerAvailableJob.getId();
            String jobId = TableNameConstant.SQL_SERVER_AVAILABLE_JOB + "_" + sqlServerAvailableJob.getId();
            serviceHelper.getQuartzManager().deleteScheduleJob(jobId);
            sqlServerAvailableJobMapper.deleteById(sqlServerAvailableJobId);
            //同时删除日志和历史日志
            sqlServerAvailableJobLogService.deleteBySqlServerAvailableJobId(sqlServerAvailableJobId);
            sqlServerAvailableJobLogHistoryService.deleteBySqlServerAvailableJobId(sqlServerAvailableJobId);
        }
    }

}